<template>
  <view class="container">
    <!-- 顶部Logo区域 -->
    <view class="header">
      <image class="logo" src="/static/logo.png" mode="aspectFit" />
      <text class="app-name">闲置换钱</text>
      <text class="slogan">让你的闲置物品产生价值</text>
    </view>

    <!-- 登录表单 -->
    <view class="form-container">
      <!-- Tab切换 -->
      <view class="tab-container">
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'login' }"
          @click="switchTab('login')"
        >
          登录
        </view>
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'register' }"
          @click="switchTab('register')"
        >
          注册
        </view>
      </view>

      <!-- 登录表单 -->
      <view v-if="activeTab === 'login'" class="form">
        <view class="input-group">
          <view class="input-item">
            <text class="input-icon">📱</text>
            <input 
              class="input-field" 
              v-model="loginForm.username" 
              placeholder="请输入手机号/用户名"
              maxlength="50"
              @input="clearError"
            />
          </view>
          <view class="input-item">
            <text class="input-icon">🔒</text>
            <input 
              class="input-field" 
              v-model="loginForm.password" 
              placeholder="请输入密码"
              :password="!showPassword"
              maxlength="20"
              @input="clearError"
            />
            <text 
              class="password-toggle" 
              @click="togglePassword"
            >
              {{ showPassword ? '👁️' : '👁️‍🗨️' }}
            </text>
          </view>
        </view>

        <view v-if="errorMessage" class="error-message">
          {{ errorMessage }}
        </view>

        <button 
          class="login-btn" 
          :class="{ 'disabled': !canLogin || loading }"
          @click="handleLogin"
          :disabled="!canLogin || loading"
        >
          {{ loading ? '登录中...' : '登录' }}
        </button>

        <view class="login-options">
          <text class="forgot-password" @click="handleForgotPassword">忘记密码？</text>
        </view>
      </view>

      <!-- 注册表单 -->
      <view v-if="activeTab === 'register'" class="form">
        <view class="input-group">
          <view class="input-item">
            <text class="input-icon">👤</text>
            <input 
              class="input-field" 
              v-model="registerForm.username" 
              placeholder="请输入用户名"
              maxlength="20"
              @input="clearError"
            />
          </view>
          <view class="input-item">
            <text class="input-icon">📱</text>
            <input 
              class="input-field" 
              v-model="registerForm.phone" 
              placeholder="请输入手机号"
              type="number"
              maxlength="11"
              @input="clearError"
            />
          </view>
          <view class="input-item">
            <text class="input-icon">📝</text>
            <input 
              class="input-field" 
              v-model="registerForm.nickname" 
              placeholder="请输入昵称(可选)"
              maxlength="20"
              @input="clearError"
            />
          </view>
          <view class="input-item">
            <text class="input-icon">📧</text>
            <input 
              class="input-field" 
              v-model="registerForm.email" 
              placeholder="请输入邮箱(可选)"
              @input="clearError"
            />
          </view>
          <view class="input-item">
            <text class="input-icon">🔒</text>
            <input 
              class="input-field" 
              v-model="registerForm.password" 
              placeholder="请输入密码(6-20位)"
              :password="!showPassword"
              maxlength="20"
              @input="clearError"
            />
            <text 
              class="password-toggle" 
              @click="togglePassword"
            >
              {{ showPassword ? '👁️' : '👁️‍🗨️' }}
            </text>
          </view>
          <view class="input-item">
            <text class="input-icon">🔒</text>
            <input 
              class="input-field" 
              v-model="registerForm.confirmPassword" 
              placeholder="请确认密码"
              :password="!showPassword"
              maxlength="20"
              @input="clearError"
            />
          </view>
        </view>

        <view v-if="errorMessage" class="error-message">
          {{ errorMessage }}
        </view>

        <!-- 协议同意 -->
        <view class="agreement-section">
          <checkbox-group @change="onAgreementChange">
            <label class="agreement-item">
              <checkbox value="agree" :checked="agreeTerms" />
              <text class="agreement-text">
                我已阅读并同意
                <text class="link" @click="viewTerms">《用户协议》</text>
                和
                <text class="link" @click="viewPrivacy">《隐私政策》</text>
              </text>
            </label>
          </checkbox-group>
        </view>

        <button 
          class="register-btn" 
          :class="{ 'disabled': !canRegister || loading }"
          @click="handleRegister"
          :disabled="!canRegister || loading"
        >
          {{ loading ? '注册中...' : '注册' }}
        </button>
      </view>
    </view>

    <!-- 其他登录方式 -->
    <view class="other-login">
      <view class="divider">
        <text class="divider-text">其他登录方式</text>
      </view>
      <view class="social-login">
        <view class="social-item" @click="handleWechatLogin">
          <text class="social-icon">💬</text>
          <text class="social-text">微信登录</text>
        </view>
        <view class="social-item" @click="handleQQLogin">
          <text class="social-icon">🐧</text>
          <text class="social-text">QQ登录</text>
        </view>
      </view>
    </view>

    <!-- 底部信息 -->
    <view class="footer">
      <text class="footer-text">© 2025 闲置换钱 v1.0.0</text>
    </view>
  </view>
</template>

<script>
import { request } from '@/utils/request.js';
import { setUserInfo, clearUserInfo } from '@/utils/auth.js';

export default {
  data() {
    return {
      activeTab: 'login', // 'login' or 'register'
      showPassword: false,
      loading: false,
      errorMessage: '',
      agreeTerms: false,
      
      // 登录表单
      loginForm: {
        username: '',
        password: ''
      },
      
      // 注册表单
      registerForm: {
        username: '',
        nickname: '',
        phone: '',
        email: '',
        password: '',
        confirmPassword: ''
      }
    }
  },
  
  computed: {
    // 是否可以登录
    canLogin() {
      return this.loginForm.username.trim() && 
             this.loginForm.password.length >= 6;
    },
    
    // 是否可以注册
    canRegister() {
      return this.registerForm.username.trim() &&
             this.registerForm.phone.trim() &&
             this.registerForm.password.length >= 6 &&
             this.registerForm.password === this.registerForm.confirmPassword &&
             this.agreeTerms;
    }
  },
  
  onLoad(options) {
    // 检查是否已登录
    this.checkLoginStatus();
    
    // 如果有参数指定注册，切换到注册tab
    if (options.tab === 'register') {
      this.activeTab = 'register';
    }
  },
  
  methods: {
    // 检查登录状态
    checkLoginStatus() {
      const token = uni.getStorageSync('token');
      const userInfo = uni.getStorageSync('userInfo');
      
      if (token && userInfo) {
        // 已登录，跳转到首页
        uni.switchTab({
          url: '/pages/index/index'
        });
      }
    },
    
    // 切换Tab
    switchTab(tab) {
      this.activeTab = tab;
      this.clearError();
    },
    
    // 清除错误信息
    clearError() {
      this.errorMessage = '';
    },
    
    // 切换密码显示
    togglePassword() {
      this.showPassword = !this.showPassword;
    },
    
    // 协议同意状态变化
    onAgreementChange(e) {
      this.agreeTerms = e.detail.value.includes('agree');
    },
    
    // 处理登录
    async handleLogin() {
      if (!this.canLogin || this.loading) return;
      
      this.clearError();
      this.loading = true;
      
      try {
        // 基本验证
        if (!this.validateLoginForm()) {
          return;
        }
        
        const response = await request({
          url: '/api/user/login',
          method: 'POST',
          data: {
            username: this.loginForm.username.trim(),
            password: this.loginForm.password
          }
        });
        
        if (response.code === 200 && response.data) {
			console.log(response.data)
          // 保存用户信息和token
          await setUserInfo(response.data);
          
          uni.showToast({
            title: '登录成功',
            icon: 'success'
          });
          
          // 延迟跳转到首页
          setTimeout(() => {
            uni.switchTab({
              url: '/pages/index/index'
            });
          }, 1000);
          
        } else {
          this.errorMessage = response.message || '登录失败，请重试';
        }
        
      } catch (error) {
        console.error('登录失败:', error);
        this.errorMessage = error?.message || '网络错误，请重试';
      } finally {
        this.loading = false;
      }
    },
    
    // 处理注册
    async handleRegister() {
      if (!this.canRegister || this.loading) return;
      
      this.clearError();
      this.loading = true;
      
      try {
        // 基本验证
        if (!this.validateRegisterForm()) {
          return;
        }
        
        const response = await request({
          url: '/api/user/register',
          method: 'POST',
          data: {
            username: this.registerForm.username.trim(),
            nickname: this.registerForm.nickname.trim() || null,
            phone: this.registerForm.phone.trim(),
            email: this.registerForm.email.trim() || null,
            password: this.registerForm.password
          }
        });
        
        if (response.code === 200 && response.data) {
          uni.showToast({
            title: '注册成功',
            icon: 'success'
          });
          
          // 自动切换到登录tab，并填入用户名
          this.activeTab = 'login';
          this.loginForm.username = this.registerForm.username;
          this.loginForm.password = '';
          
          // 清空注册表单
          this.resetRegisterForm();
          
        } else {
          this.errorMessage = response.message || '注册失败，请重试';
        }
        
      } catch (error) {
        console.error('注册失败:', error);
        this.errorMessage = error?.message || '网络错误，请重试';
      } finally {
        this.loading = false;
      }
    },
    
    // 验证登录表单
    validateLoginForm() {
      if (!this.loginForm.username.trim()) {
        this.errorMessage = '请输入用户名或手机号';
        return false;
      }
      
      if (this.loginForm.password.length < 6) {
        this.errorMessage = '密码至少6位';
        return false;
      }
      
      return true;
    },
    
    // 验证注册表单
    validateRegisterForm() {
      if (!this.registerForm.username.trim()) {
        this.errorMessage = '请输入用户名';
        return false;
      }
      
      if (this.registerForm.username.length < 2) {
        this.errorMessage = '用户名至少2个字符';
        return false;
      }
      
      if (!this.registerForm.phone.trim()) {
        this.errorMessage = '请输入手机号';
        return false;
      }
      
      if (!/^1[3-9]\d{9}$/.test(this.registerForm.phone)) {
        this.errorMessage = '请输入有效的手机号';
        return false;
      }
      
      if (this.registerForm.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.registerForm.email)) {
        this.errorMessage = '请输入有效的邮箱地址';
        return false;
      }
      
      if (this.registerForm.password.length < 6) {
        this.errorMessage = '密码至少6位';
        return false;
      }
      
      if (this.registerForm.password !== this.registerForm.confirmPassword) {
        this.errorMessage = '两次输入的密码不一致';
        return false;
      }
      
      if (!this.agreeTerms) {
        this.errorMessage = '请先同意用户协议和隐私政策';
        return false;
      }
      
      return true;
    },
    
    // 重置注册表单
    resetRegisterForm() {
      this.registerForm = {
        username: '',
        nickname: '',
        phone: '',
        email: '',
        password: '',
        confirmPassword: ''
      };
      this.agreeTerms = false;
    },
    
    // 忘记密码
    handleForgotPassword() {
      uni.showModal({
        title: '忘记密码',
        content: '请联系客服：400-xxx-xxxx',
        showCancel: false
      });
    },
    
    // 微信登录
    handleWechatLogin() {
      uni.showToast({
        title: '微信登录功能开发中',
        icon: 'none'
      });
    },
    
    // QQ登录
    handleQQLogin() {
      uni.showToast({
        title: 'QQ登录功能开发中',
        icon: 'none'
      });
    },
    
    // 查看用户协议
    viewTerms() {
      uni.navigateTo({
        url: '/pages/webview/index?url=https://example.com/terms&title=用户协议'
      });
    },
    
    // 查看隐私政策
    viewPrivacy() {
      uni.navigateTo({
        url: '/pages/webview/index?url=https://example.com/privacy&title=隐私政策'
      });
    }
  }
}
</script>

<style scoped>
/* 容器样式 */
.container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40px 20px 20px;
}

/* 头部Logo区域 */
.header {
  text-align: center;
  margin-bottom: 60px;
}

.logo {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin-bottom: 16px;
}

.app-name {
  display: block;
  font-size: 28px;
  font-weight: bold;
  color: #fff;
  margin-bottom: 8px;
}

.slogan {
  display: block;
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
}

/* 表单容器 */
.form-container {
  background: #fff;
  border-radius: 16px;
  padding: 0;
  margin-bottom: 40px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

/* Tab切换 */
.tab-container {
  display: flex;
  border-bottom: 1px solid #f0f0f0;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 16px 0;
  font-size: 16px;
  color: #666;
  position: relative;
  cursor: pointer;
  transition: all 0.3s;
}

.tab-item.active {
  color: #667eea;
  font-weight: bold;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 50%;
  transform: translateX(-50%);
  width: 40px;
  height: 3px;
  background: #667eea;
  border-radius: 2px;
}

/* 表单样式 */
.form {
  padding: 24px;
}

.input-group {
  margin-bottom: 24px;
}

.input-item {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border-radius: 12px;
  padding: 0 16px;
  margin-bottom: 16px;
  border: 2px solid transparent;
  transition: all 0.3s;
}

.input-item:focus-within {
  border-color: #667eea;
  background: #fff;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.input-icon {
  font-size: 18px;
  margin-right: 12px;
  width: 20px;
  text-align: center;
}

.input-field {
  flex: 1;
  height: 50px;
  border: none;
  background: transparent;
  font-size: 16px;
  outline: none;
}

.password-toggle {
  font-size: 18px;
  padding: 8px;
  cursor: pointer;
  opacity: 0.6;
  transition: opacity 0.3s;
}

.password-toggle:hover {
  opacity: 1;
}

/* 错误信息 */
.error-message {
  color: #ff4757;
  font-size: 14px;
  margin-bottom: 16px;
  padding: 8px 12px;
  background: #fff5f5;
  border-radius: 8px;
  border-left: 3px solid #ff4757;
}

/* 按钮样式 */
.login-btn,
.register-btn {
  width: 100%;
  height: 50px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 16px;
  transition: all 0.3s;
}

.login-btn:active,
.register-btn:active {
  transform: translateY(1px);
}

.login-btn.disabled,
.register-btn.disabled {
  background: #ccc;
  color: #999;
  transform: none;
}

/* 登录选项 */
.login-options {
  text-align: center;
}

.forgot-password {
  color: #667eea;
  font-size: 14px;
  cursor: pointer;
}

/* 协议同意 */
.agreement-section {
  margin-bottom: 24px;
}

.agreement-item {
  display: flex;
  align-items: flex-start;
}

.agreement-text {
  flex: 1;
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  margin-left: 8px;
}

.link {
  color: #667eea;
  cursor: pointer;
}

/* 其他登录方式 */
.other-login {
  margin-bottom: 40px;
}

.divider {
  text-align: center;
  position: relative;
  margin-bottom: 24px;
}

.divider::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background: rgba(255, 255, 255, 0.3);
}

.divider-text {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: rgba(255, 255, 255, 0.8);
  padding: 0 16px;
  font-size: 14px;
  position: relative;
}

.social-login {
  display: flex;
  justify-content: center;
  gap: 32px;
}

.social-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  transition: transform 0.3s;
}

.social-item:active {
  transform: scale(0.95);
}

.social-icon {
  width: 50px;
  height: 50px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  margin-bottom: 8px;
}

.social-text {
  color: rgba(255, 255, 255, 0.8);
  font-size: 12px;
}

/* 底部信息 */
.footer {
  text-align: center;
}

.footer-text {
  color: rgba(255, 255, 255, 0.6);
  font-size: 12px;
}
</style>